<template>
  <el-upload
    v-model:file-list="formInline.articlePictureUp"
    action="#"
    :limit="1"
    :on-change="handleBeforeUpload"
    list-type="picture-card"
    :auto-upload="false"
  >
    <template #trigger>
      <el-button type="primary">选择图片</el-button>
    </template>
  </el-upload>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
// 定义 props
const props = defineProps({ 
  modelValue: String, 
  maxSize: {
    type: Number,
    default: 5 // 默认5MB
  }
})

const emit = defineEmits(['update:modelValue'])

const formInline = ref({ articlePictureUp: props.modelValue ? [{ url: props.modelValue }] : [] })

watch(
  () => props.modelValue,
  (newVal) => {
    formInline.value.articlePictureUp = newVal ? [{ url: newVal }] : []
  }
)

const handleBeforeUpload = (file) => {
  // 检查文件大小
  const fileSizeMB = file.size / 1024 / 1024
  if (fileSizeMB > props.maxSize) {
    ElMessage.error(`上传文件大小不能超过 ${props.maxSize}MB!`)
    return false
  }
  
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  const reader = new FileReader()
  reader.onload = (e) => {
    emit('update:modelValue', e.target.result)
    formInline.value.articlePictureUp = [{ url: e.target.result }]
  }
  reader.readAsDataURL(file.raw)
}
</script>

<style scoped>
/* 样式部分 */
</style>
